# \zennotac-backend\app\routes\download.py
from fastapi import APIRouter, HTTPException, Query
from app.utils.filename_helper import safe_join

from fastapi.responses import FileResponse
from app.config.base_setting import OCR_OUTPUT_FOLDER, ARCHIVE_OCR_OUTPUT_FOLDER, EXCEL_OUTPUT_FOLDER, ARCHIVE_EXCEL_OUTPUT_FOLDER, backend_logger
import os

router = APIRouter()

@router.get("/download/ocred-file")
async def download_file(filename: str = Query(...)):
    """Download ocred PDF file for front end."""
    file_path = safe_join(OCR_OUTPUT_FOLDER, filename)

    if os.path.exists(file_path):
        backend_logger.info(f"Serving file download: {file_path}")
        return FileResponse(path=file_path, filename=filename, media_type='application/octet-stream')
    
    # Check archive fallback
    archive_path = safe_join(ARCHIVE_OCR_OUTPUT_FOLDER, filename)
    if os.path.exists(archive_path):
        backend_logger.info(f"Serving file download: {archive_path}")
        return FileResponse(path=archive_path, filename=filename, media_type='application/octet-stream')

    raise HTTPException(status_code=404, detail=f"File {filename} not found.")

@router.get("/download/excel-file")
async def download_excel_file(filename: str = Query(...)):
    """Download Excel file after ocr-ed file be excel-ed by a backend script."""
    file_path = safe_join(EXCEL_OUTPUT_FOLDER, filename)

    if os.path.exists(file_path):
        backend_logger.info(f"Serving file download: {file_path}")
        return FileResponse(path=file_path, filename=filename, media_type='application/octet-stream')
    
    # Check archive fallback
    archive_path = safe_join(ARCHIVE_EXCEL_OUTPUT_FOLDER, filename)
    if os.path.exists(archive_path):
        backend_logger.info(f"Serving file download: {archive_path}")
        return FileResponse(path=archive_path, filename=filename, media_type='application/octet-stream')

    raise HTTPException(status_code=404, detail=f"File {filename} not found.")
